/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * 迭代实现
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    if(!root)return [];
    let res = [];
    let cur = root;
    let stack = [];

    while(cur){

        stack.push(cur);
        res.push(cur.val);

        while(cur.left){
            cur = cur.left;
            stack.push(cur);
            res.push(cur.val);
        }

        while(stack.length>0){
            cur = stack.pop();
            if(cur.right){
                cur = cur.right;
                break;
            }
            cur = null;
        }

    }

    return res;

};